﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ValueProviders;
using TasksManager.App.AuthenticationHeaders;
using VehicleRental.Data;
using VehicleRental.Models;

namespace VehicleRental.API.Controllers
{
    public class FundsController : BaseApiController
    {
        //withdraw() -> remove money from account
        [HttpPut, ActionName("withdraw")]
        public HttpResponseMessage WithdrawFunds( [ValueProvider(typeof(HeaderValueProviderFactory<string>))]
            string accessToken, decimal sum)
        {
            return this.ExecuteOperationAndHandleExceptions(() =>
            {
                VehicleRentalContext context = new VehicleRentalContext();

                var user = this.GetUserByAccessToken(accessToken, context);
 
                Card currentCard = context.Cards.Include("Users").FirstOrDefault(c => c.User.Id == user.Id);

                if (currentCard == null)
                {
                    throw new ArgumentException("Card doesn't exist");
                }

                decimal existingFunds = currentCard.TotalFunds;

                if (existingFunds < sum)
                {
                    throw new ArgumentException("Not enough funds in the card");
                }
                if (sum < 0)
                {
                    throw new ArgumentException("The sum to withdraw should be positive");
                }

                currentCard.TotalFunds -= sum;
                context.SaveChanges();

                var response = this.Request.CreateResponse(HttpStatusCode.NoContent);

                return response;
            });
        }

        //deposit() -> add money to account
        [HttpPut, ActionName("deposit")]
        public HttpResponseMessage DepositFunds([ValueProvider(typeof(HeaderValueProviderFactory<string>))]
            string accessToken, decimal sum)
        {
            return this.ExecuteOperationAndHandleExceptions(() =>
            {
                VehicleRentalContext context = new VehicleRentalContext();

                var user = this.GetUserByAccessToken(accessToken, context);
                if (sum <= 0)
                {
                    throw new ArgumentException("The amount to deposit must be positive");
                }

                Card currentCard = context.Cards.Include("Users").FirstOrDefault(c => c.User.Id == user.Id);

                if (currentCard == null)
                {
                    throw new ArgumentException("Card doesn't exist");
                }

                currentCard.TotalFunds += sum;

                context.SaveChanges();

                var response = this.Request.CreateResponse(HttpStatusCode.NoContent);

                return response;
            });
        }
    }
}
